﻿using Microsoft.IdentityModel.Tokens;
using OA.Infrastructure.Authentication.Abstractions;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

namespace OA.Infrastructure.Authentication.Jwt;

public class JwtTokenHandler : ITokenHandler
{
    private readonly IConfiguration _cfg;

    public JwtTokenHandler(IConfiguration cfg)
    {
        _cfg = cfg;
    }

    private readonly JwtSecurityTokenHandler _handler = new();

    public Token CreateToken(ICollection<Claim> claims)
    {
        var token = new Token();

        var issuer = _cfg["Jwt:Issuer"];
        var audience = _cfg["Jwt:Audience"];
        var expiresTime = DateTime.UtcNow.AddSeconds(token.ExpireIn);
        var securityKey = _cfg["Jwt:SecurityKey"];

        var symmetricKey = new SymmetricSecurityKey(Convert.FromBase64String(securityKey));
        var credentials = new SigningCredentials(symmetricKey, SecurityAlgorithms.HmacSha256);

        var header = new JwtHeader(credentials);
        var payload = new JwtPayload(issuer, audience, claims, null, expiresTime);

        token.AccessToken = _handler.WriteToken(new JwtSecurityToken(header, payload));

        return token;
    }
}